package com.dehui.traders.ui.stockdetail;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dehui.traders.R;
import com.dehui.traders.ui.predict.PredictActivity;

/**
 * Created by hqq on 18.5.11.
 */

public class SuspendView extends RelativeLayout {

    // 悬浮栏位置
    private final static int LEFT   = 0;
    private final static int RIGHT  = 1;
    private final static int TOP    = 3;
    private final static int BUTTOM = 4;
    private final int mClickTimeout;

    private int                        dpi;
    private int                        screenHeight;
    private int                        screenWidth;
    private LayoutParams wmParams;
    private WindowManager              wm;
    private float                      x, y;
    private       float    mTouchStartX;
    private       float    mTouchStartY;
    private       boolean  isScroll;
    private       long     mTime;
    private final TextView tvNum;
    private ViewGroup rlMain;

    public SuspendView(final Activity activity, ViewGroup rlMain, String code, String name) {
        super(activity);
        this.rlMain = rlMain;
        View view = LayoutInflater.from(activity).inflate(R.layout.tip_suspend_view, this);
        tvNum = (TextView) view.findViewById(R.id.tv_num);
        wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        //通过像素密度来设置按钮的大小
        dpi = dp2px(activity, 45);
        //屏宽
        screenWidth = rlMain.getMeasuredWidth();
        //屏高
        screenHeight = rlMain.getMeasuredHeight();

        //布局设置
        wmParams = new LayoutParams(dpi,dpi);
        // 设置window type
        wmParams.topMargin = (screenHeight - dpi) - 300;
        wmParams.leftMargin = screenWidth - dpi - 10;
        rlMain.addView(this, wmParams);
        hide();

        mClickTimeout = ViewConfiguration.getPressedStateDuration()
                + ViewConfiguration.getTapTimeout();

        this.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mTime < mClickTimeout) {
                    Intent intent = new Intent(activity, PredictActivity.class);
                    intent.putExtra("code",code);
                    intent.putExtra("name",name);
                    activity.startActivity(intent);
                }

            }
        });

    }

    public static int dp2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public void show() {
        setVisibility(View.VISIBLE);
    }


    public void hide() {
        setVisibility(View.GONE);
    }

    public void destory() {
        hide();
        wm.removeViewImmediate(this);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 获取相对屏幕的坐标， 以屏幕左上角为原点
        x = event.getRawX();
        y = event.getRawY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // setBackgroundDrawable(openDrawable);
                // invalidate();
                // 获取相对View的坐标，即以此View左上角为原点
                mTouchStartX = event.getX();
                mTouchStartY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                if (isScroll) {
                    updateViewPosition();
                } else {
                    // 当前不处于连续滑动状态 则滑动小于图标1/3则不滑动
                    if (Math.abs(mTouchStartX - event.getX()) > dpi / 3
                            || Math.abs(mTouchStartY - event.getY()) > dpi / 3) {
                        updateViewPosition();
                    } else {
                        break;
                    }
                }
                isScroll = true;
                break;
            case MotionEvent.ACTION_UP:
                // 拖动
                mTime = event.getEventTime() - event.getDownTime();

                if (isScroll) {
                    autoView();
                    // setBackgroundDrawable(closeDrawable);
                    // invalidate();
                } else {
                    // 当前显示功能区，则隐藏
                    // setBackgroundDrawable(openDrawable);
                    // invalidate();

                }
                isScroll = false;
                mTouchStartX = mTouchStartY = 0;
                break;
        }
        return super.onTouchEvent(event);
    }

    /**
     * 自动移动位置
     */
    private void autoView() {
        // 得到view在屏幕中的位置
        int[] location = new int[2];
        getLocationOnScreen(location);
        //左侧
        if (location[0] < screenWidth / 2 - dpi / 2) {
            updateViewPosition(LEFT);
        } else {
            updateViewPosition(RIGHT);
        }
    }

    /**
     * 手指释放更新悬浮窗位置
     */
    private void updateViewPosition(int l) {
        ValueAnimator valueAnimator = null;
        switch (l) {
            case LEFT:
                //                wmParams.x = 0;
                valueAnimator = ValueAnimator.ofFloat(x, 0);
                break;
            case RIGHT:
                //                int x = screenWidth - dpi;
                //                wmParams.x = x - 10;
                valueAnimator = ValueAnimator.ofFloat(x, screenWidth - dpi - 10);
                break;
            //            case TOP:
            ////                wmParams.y = 0;
            ////                break;
            ////            case BUTTOM:
            ////                wmParams.y = screenHeight - dpi;
            ////                break;
        }
        if (valueAnimator == null)
            valueAnimator = ValueAnimator.ofFloat(x, screenWidth - dpi - 10);
        valueAnimator.setDuration(200);
        valueAnimator.setInterpolator(new AccelerateInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                float value = (float) valueAnimator.getAnimatedValue();
                wmParams.leftMargin = (int) value;
                rlMain.updateViewLayout(SuspendView.this, wmParams);
            }
        });
        valueAnimator.start();
        //        wm.updateViewLayout(this, wmParams);

    }

    // 更新浮动窗口位置参数
    private void updateViewPosition() {
        if (x < screenWidth - dpi)
            wmParams.leftMargin = (int) (x - mTouchStartX);
        //是否存在状态栏（提升滑动效果）
        // 不设置为全屏（状态栏存在） 标题栏是屏幕的1/25
        if (y > rlMain.getTop() + dpi /2 && y < rlMain.getBottom() - dpi / 2)
            wmParams.topMargin = (int) (y - mTouchStartY - dpi);

        rlMain.updateViewLayout(this, wmParams);
    }
}